package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.spzx.api.cart.api.RemoteCartService;
import com.spzx.api.cart.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.order.domain.*;
import com.spzx.order.service.OrderInfoService;
import com.spzx.user.api.RemoteUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;



import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl implements OrderInfoService {
    @Autowired
    RemoteCartService remoteCartService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RemoteUserAddressService remoteUserAddressService;

    @Override
    public TradeVo getOrderTradeData() {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        //从redis里面获取购物车选中商品的集合
        R<List<CartInfo>> cartInfoListR = remoteCartService.getCartsWithChecked(SecurityConstants.INNER);
        if (R.FAIL == cartInfoListR.getCode()) {
            throw new ServiceException(cartInfoListR.getMsg());
        }
        List<CartInfo> cartInfoList = cartInfoListR.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("购物车无选中商品");
        }
        //将集合泛型从购物车改为订单明细（把购物车的信息变为订单信息,得到List<OrderItem>和 totalPrice）
        List<OrderItem> orderItemList = null;
        BigDecimal totalAmount = new BigDecimal(0);
        orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            //copyProperties(源对象, 目标对象)。
            BeanUtils.copyProperties(cartInfo, orderItem);
            //SkuPrice特殊处理
            orderItem.setSkuPrice(cartInfo.getSkuPrice());
            return orderItem;
        }).collect(Collectors.toList());
        //订单总金额
//        orderItemList.forEach(orderItem -> {
//            BigDecimal skuPrice = orderItem.getSkuPrice();
//            totalAmount += skuPrice;
//        });
        for (OrderItem orderItem : orderItemList) {
            totalAmount =totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        //渲染订单确认页面-生成用户流水号
        TradeVo tradeVo = new TradeVo();
        String tradeNo = this.getTradeNo(userId);
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        return tradeVo;

    }

    //提交订单
//    用户在结算页面点击提交订单按钮，那么此时就需要保存订单信息(order_info)、
//    订单项信息(order_item)及记录订单日志(order_log)，下单成功重定向到订单支付页面
    /*
    、@Schema(description = "结算总金额")
    private OrderItem orderItem;

    @Schema(description = "用户地址")
    private String userAddress;

    @Schema(description = "运费")
    private Long feighFee;

    @Schema(description = "备注")
    private String remark;
     */
    @Override
    public void submitOrder(SubmitVo submitVo) {
        //根据userId获取用户信息
//        remoteUserAddressService.getUserAddress()
//        //保存订单信息
//        OrderInfo orderInfo = new OrderInfo();
//        orderInfo.setUserId(SecurityContextHolder.getUserId());
//        orderInfo.setNickName();
//        orderInfo.setOrderNo();
//        orderInfo.setCouponId();
//        orderInfo.setTotalAmount();
//        orderInfo.setCouponAmount();
//        orderInfo.setOriginalTotalAmount();
//        orderInfo.setFeightFee(submitVo.getFeighFee());
//        orderInfo.setOrderStatus();
//        orderInfo.setReceiverName();
//        orderInfo.setReceiverPhone();
//        orderInfo.setReceiverTagName();
//        orderInfo.setReceiverProvince();
//        orderInfo.setReceiverCity();
//        orderInfo.setReceiverDistrict();
//        orderInfo.setReceiverAddress(submitVo.getUserAddress());
//        orderInfo.getPaymentTime();
//        orderInfo.getReceiveTime();
//        orderInfo.setCancelTime();
//        orderInfo.setCancelReason();
//        //保存订单项信息
//        OrderItem orderItem = new OrderItem();
//        BeanUtils.copyProperties(submitVo.getOrderItem(), orderItem);
//        //保存记录订单日志
//        OrderLog orderLog = new OrderLog();
//        orderLog.setOrderId();
//        orderLog.setOperateUser();
//        orderLog.setProcessStatus();
//        orderLog.setNote(submitVo.getRemark());
        //下单成功重定向到订单支付页面
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    public String getTradeNo(Long userId){
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo"+userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo,5, TimeUnit.MINUTES);
        return tradeNo;
    }

}
